package com.tbit.uqbike.client.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.tbit.uqbike.client.constant.*;
import com.tbit.uqbike.client.dao.core.UserToAgentDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 区域押金
 *
 * @Author: chen
 * @Description: 区域押金
 * @Date: 创建于 16:22 2020/1/3
 */
@Controller
@RequestMapping("/adAccountDeposit")
public class AdAccountDepositController {
    @Autowired
    private GeoService geoService;
    @Autowired
    private AdAccountDepositService adAccountDepositService;
    @Autowired
    private GiftCardUserService giftCardUserService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private UserToAgentDao userToAgentDao;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private AgentDepositVipService agentDepositVipService;
    @Autowired
    private BrandShareRelationService brandShareRelationService;
    /**
     * 通过位置获取区域信息
     *
     * @param token     令牌
     * @param accountId 帐户id
     * @param lo        经度
     * @param la        纬度
     * @param mapType   地图类型
     * @param response  响应
     * @ignoreParams request
     */
    @RequestMapping("/getByLocation")
    public void getByLocation(String token, Integer accountId, Double lo, Double la, Integer mapType, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Assert.notNull(accountId, "-10001", "品牌id不能为空");
            Assert.notNull(lo, "-2001", "经度不能为空");
            Assert.notNull(la, "-2002", "纬度不能为空");
            if (mapType == null) {
                mapType = MapConstant.MAP_GOOGLE;
            }
            String lang = request.getHeader("lang");
            if (lang == null) {
                lang = "cn";
            }
            Integer agentId = null;
            if (token != null) {
                User user = tokenService.getUser(token);
                if (user != null) {
                    agentId = geoService.getBelongAccountAndUserId(accountId, lo, la, mapType, user.getUserId());
                }
            }
            if (agentId == null) {
                agentId = geoService.getBelongAccount(accountId, lo, la, mapType);
            }

            MoneyData moneyData = new MoneyData(0, 0, 0, 0, 0, 0, 0);
            if (agentId == null) {
                if (token != null) {
                    User user = tokenService.getUser(token);
                    if (user != null) {
                        // user=userService.getByUserId(user.getUserId());
                        UserToAgent userToAgent = userToAgentDao.getByUserId(user.getUserId());
                        if (userToAgent != null) {
                            agentId = userToAgent.getAccountId();
                        }
                        /**校验实名认证用户是否在其他品牌已经实名*/
                        brandShareRelationService.handleNameAuthByBrandShare(user);
                        moneyData.setNameAuth(user.getNameAuth() ? 1 : 0);
                    }
                }
            }
            if (agentId != null) {
                if (token != null) {
                    User user = tokenService.getUser(token);
                    if (user != null) {
                        User userDB = userService.getByUserId(user.getUserId());
                        moneyData.setActualMoney((int) (userDB.getMoney() - userDB.getRideMoney()));
                        moneyData.setUseDeposit(userDB.getDepositMoney().intValue());
                        /**获取区域用户余额*/
                        GiftCardUser giftCardUser = giftCardUserService.getByUserId(user.getUserId(), agentId);
                        if (giftCardUser != null) {
                            moneyData.setCardMoney(giftCardUser.getMoney());
                        }
                        if (moneyData.getDepositMoney() > moneyData.getUseDeposit() && userDB.getDepositState() == 1) {
                            moneyData.setDepositStatus(DepositStateConstant.DEPOSIT_STATE_MONEY_LESS);
                        } else {
                            moneyData.setDepositStatus(userDB.getDepositState());
                        }
                        //兼容购买免押卡不需要提交押金
                        Boolean isFreeDeposit = Optional.ofNullable(agentDepositVipService.getByUserId(user.getUserId(), agentId))
                                .map(agentDepositVip -> DateUtil.between(DateUtil.parseDateTime(agentDepositVip.getExpireDt()+" 23:59:59"),
                                        DateUtil.date(), DateUnit.SECOND)>0).orElse(false);
                        if (isFreeDeposit){
                            moneyData.setDepositStatus(DepositStateConstant.DEPOSIT_STATE_VIRTUAL);
                        }
                        moneyData.setTotalMoney((int) ((userDB.getMoney() - userDB.getRideMoney()) + moneyData.getCardMoney()));
                        /**校验实名认证用户是否在其他品牌已经实名*/
                        brandShareRelationService.handleNameAuthByBrandShare(user);
                        moneyData.setNameAuth(user.getNameAuth() ? 1 : 0);
                    }
                }
                /**获取区域押金*/
                AdAccountDeposit adAccountDeposit = adAccountDepositService.getByAccountId(agentId);
                if (adAccountDeposit != null) {
                    moneyData.setDepositMoney(adAccountDeposit.getDeposit());
                }
                moneyData.setAccountId(agentId);
                /**默认学生认证关闭*/
                moneyData.setStudentAuth(0);
                /**还车模式*/
                AccountConfig accountConfig = accountConfigService.getByAccountId(agentId);
                if (accountConfig != null) {
                    moneyData.setModelType(accountConfig.getReturnModel());
                    /**是否需要实名认证*/
                    //todo 5.1.1  判断用户是否需要实名认证
                    moneyData.setNameAuth((moneyData.getNameAuth() == null || moneyData.getNameAuth() !=1) ? accountConfig.getNameAuth() : 1);
                    moneyData.setAppoint(accountConfig.getAppoint());
                    moneyData.setWxModelMsg(accountConfig.getWxModelMsg());
                    moneyData.setWxZffDeposit(accountConfig.getWxZffDeposit());
                    moneyData.setWxZffMm(accountConfig.getWxZffMm());
                    moneyData.setFaceCheck(accountConfig.getFaceCheck());
                    /**开电池锁功能*/
                    if (accountConfig.getBatteryLock() != null && accountConfig.getBatteryLock() == 1) {
                        moneyData.setBatteryLock(accountConfig.getBatteryLock());
                    }
                    moneyData.setStudentAuth(accountConfig.getStudentAuth());
                }

                /**区域配置*/
                List<AccountConfigExt> accountConfigExts = cacheService.getAccountConfigExt(agentId);
                if (accountConfigExts.size() > 0) {
                    for (AccountConfigExt a : accountConfigExts) {
                        if (AccountConfigExtConstant.ACCOUNTCONFIG_SHOWREFUND.equalsIgnoreCase(a.getParamKey())) {
                            moneyData.setShowRefund(Integer.valueOf(a.getParamValue()));
                        } else if (AccountConfigExtConstant.ACCOUNTCONFIG_SHOWFRANCHISEE.equalsIgnoreCase(a.getParamKey())) {
                            moneyData.setShowFranchisee(Integer.valueOf(a.getParamValue()));
                        } else if (AccountConfigExtConstant.ACCOUNTCONFIG_NEWUSER.equalsIgnoreCase(a.getParamKey())) {
                            moneyData.setNewUser(Integer.valueOf(a.getParamValue()));
                        } else if (AccountConfigExtConstant.ACCOUNTCONFIG_MODEL.equalsIgnoreCase(a.getParamKey())) {
                            moneyData.setWeixin_model(Integer.valueOf(a.getParamValue()));
                        }
                    }
                }
            }
            ;
            /**兼容区域外体现功能*/
            BrandRemoteConfig brandRemoteConfig = cacheService.getBrandRemoteConfig(accountId,
                    BrandConstant.WITHDRAW_OUT_AREA);
            if (brandRemoteConfig != null) {
                Integer button = Integer.valueOf(brandRemoteConfig.getParamKV().substring(brandRemoteConfig.getParamKV().indexOf("=") + 1));
                if (button == 1) {
                    moneyData.setShowRefund(button);
                }
            }
            /**兼容国际化返回金额缩写及符号*/
            if (lang.equalsIgnoreCase(LocalData.CN)) {
                moneyData.setAbbreviation("CNY");
                moneyData.setSymbol("¥");
            } else {
                moneyData.setAbbreviation("USD");
                moneyData.setSymbol("$");
            }
            map.put(ResponseCode.DATA, moneyData);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    public Integer getBrandConfig(Integer accountId, Integer type) {
        BrandRemoteConfig brandRemoteConfig = cacheService.getBrandRemoteConfig(accountId,
                type);
        if (brandRemoteConfig != null) {
            Integer button = Integer.valueOf(brandRemoteConfig.getParamKV().substring(brandRemoteConfig.getParamKV().indexOf("=") + 1));
            if (button == 1) {
                return 1;
            }
        }
        return 0;
    }
}
